// ResultWriter.java
//
// ICS 22 / CSE 22 Winter 2010
// Project #1: Perfect Candidate
//
// ResultWriter consists of one static method, writeResults(), which takes a
// filename and a Ballot and writes the final results of the election into
// an output file with the given filename.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;


public class ResultWriter
{
	// writeResults() takes a filename and a Ballot and writes the final
	// results of the election into an output file with the given filename.
	// If the file cannot be written, an IOException is thrown.
	public static void writeResults(String filename, Ballot ballot)
	throws IOException
	{
		
		try{
			String outString = "";
			outString += "RESULTS - " + ballot.getOfficeName() + "\n";
			outString += "----------";
			for(int i = 0; i < ballot.getOfficeName().length(); ++i){
				outString += "-";
			}
			outString += "\n";
			int winnerIndex = -1;
			int winnerVoteCount = -1;
			boolean tie = false;
			ArrayList<Candidate> candidates = ballot.getCandidates();
			for(int i = 0; i < ballot.getCandidates().size(); ++i){
				outString += String.format("%-10s %10d\n", candidates.get(i).toString(), candidates.get(i).getVoteCount());
				
				if(winnerVoteCount < candidates.get(i).getVoteCount()){
					winnerIndex = i;
					winnerVoteCount = candidates.get(i).getVoteCount();
					tie = false;
				}
				else if(winnerVoteCount == candidates.get(i).getVoteCount()){
					tie = true;
				}
			}
			outString += (!tie)?"WINNER:" + candidates.get(winnerIndex).toString():
								"NO WINNER";
			BufferedWriter out = new BufferedWriter(new FileWriter(filename));
			out.write(outString);
			out.close();
		}
		catch(IOException e){
			e.printStackTrace();
		}
	}
}
